/*
 * Copyright (C) 2020 Agrui
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "ParameterCheck.h"
#include "OSMemory.h"
#include "IpcChannel.h"
#include "IpcChannelManager.h"

IpcChannel* newIpcChannel(int id) {
    IpcChannel* channel = OS_ALLOC_AND_RESET(IpcChannel);
    PARAMTER_CHECK_RETURN_NULL(channel);
    channel->channelId = id;
    channel->channelSize = 4096;
    return channel;
}

void initIpcChannel(int id, IpcChannel* channel) {
    PARAMTER_CHECK_RETURN_VOID(channel);
    channel->channelId = id;
    channel->channelSize = 4096;
}



void sendChannelAsyncData(IpcChannel* channel, IpcDataHeadInfo* header, void* data, int dataLen) {
    PARAMTER_CHECK_RETURN_VOID(channel);
    if (channel->sendDataRequest) {
        channel->sendDataRequest((void*)channel, header, data, dataLen);
    }
}
void sendChannelData(IpcChannel* channel, void* data, int dataLen) {
    PARAMTER_CHECK_RETURN_VOID(channel);
    if (channel->sendData) {
        channel->sendData((void*)channel, data, dataLen);
    }
}

void registerChannelReceiveCallback(IpcChannel* channel, onDataReceiveCallback callback, void* callbackData) {
    PARAMTER_CHECK_RETURN_VOID(channel);
    channel->dataReceiveCallback = callback;
    channel->dataReceiveCallbackData = callbackData;
    if (channel->registerDataCallback) {
        channel->registerDataCallback(callback);
    }
}

void unregisterChannelReceiveCallback(IpcChannel* channel) {
    PARAMTER_CHECK_RETURN_VOID(channel);
    channel->dataReceiveCallback = NULL;
    if (channel->unregisterDataCallback) {
        channel->unregisterDataCallback();
    }
}

void registerChannelStateChanged(IpcChannel* channel, onChannelStateChangedCallback callback, void* callbackData) {
    channel->stateChangedCallback = callback;
    channel->stateCallbackData = callbackData;
}
void unregisterChannelStateChanged(IpcChannel* channel) {
    channel->stateChangedCallback = NULL;
}

void onIpcChannelDataReceive(int id, void* data, int dataLen) {
    IpcChannelManager* manager = getDefaultIpcChannelManager();
    IpcChannel* channel = getChannel(manager, id);
    if (channel && channel->dataReceiveCallback) {
        channel->dataReceiveCallback(channel->dataReceiveCallbackData, id, data, dataLen);
    }
}

void deleteIpcChannel(IpcChannel* channel) {
    PARAMTER_CHECK_RETURN_VOID(channel);
    OS_FREE(channel);
}

